import settings
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from models import *
import os
from google.appengine.ext.webapp import template
from django.utils import simplejson as json
from datetime import date, datetime, timedelta
import logging
from views.cal import overlap


def make_key(ticket):
    return "%s" % (ticket.id)

class BacklogHandler(webapp.RequestHandler):

    def get(self, project_name):
        backlog = Ticket.gql('WHERE project = :1 and milestone = :2 and status in :3 ORDER by category', project_name, None, ['New', 'Accepted', 'Started'])
        self.response.out.write('var backlog = %s;' % (
            json.dumps([t.to_dict() for t in backlog]), ))

class MilestoneTicketsHandler(webapp.RequestHandler):

    def get(self):
        tickets = Ticket.gql('WHERE milestone != :1', None)
        self.response.out.write('var tickets = %s;' % (
            json.dumps([t.to_dict() for t in tickets]), ))
    
class MilestonesHandler(webapp.RequestHandler):
    def get(self):
        data = []
        earliest = date.today() - timedelta(days=17)
        milestones = Milestone.gql(
            'WHERE due >= :1 ORDER by due asc', 
            earliest)
        milestones2 = list(Milestone.gql(
                'WHERE due >= :1 ORDER by due asc', 
                earliest))
        all_tickets = Ticket.gql('WHERE milestone in :1', [str(m.name.split('-')[1]) for m in milestones2])
        def filterf(ticket):
            passes = False
            for m in milestones2:
                if ticket.project == m.project.name and ("Milestone-%s" % (ticket.milestone, )) == m.name:
                    passes = True
            return passes
            
        all_tickets = [t for t in all_tickets if filterf(t)]
        latest = None
        for milestone in milestones:
            data.append(milestone.to_dict())
            if latest is None or milestone.due > latest:
                latest = milestone.due
        milestones = data
        latest = latest + timedelta(days=40)
        dates = []
        day = earliest
        oneday = timedelta(days=1)
        while day < latest:
            if day.weekday() < 5:
                dates.append(dict(
                    date=str(day),
                    label=day.strftime('%b %d, %Y'),
                    weekday=day.strftime('%a')[0]
                ))
            day = day + oneday
        
        committers = dict()
        for c in Committer.all():
            for alias in c.aliases:
                committers[alias] = dict(
                    name=c.name or c.aliases[0], 
                    aliases=c.aliases, 
                    gravatar=c.gravatar(), 
                    key=str(c.key()),
                )
        
        today = date.today()
        if today.weekday() > 4:
            today = today + timedelta(days=6 - today.weekday() + 1)
        
        # raise Exception( earliest, latest)
        start = datetime(earliest.year, earliest.month, earliest.day)
        end = datetime(latest.year, latest.month, latest.day)
        holidays = [o.to_dict() for o in Holiday.all() if overlap([start, end], [o.start, o.end])]
        obligations = [o.to_dict() for o in Obligation.all() if overlap([start, end], [o.start, o.end])]
        self.response.out.write('var all_tickets = %s; var committers = %s; var milestones = %s; var holidays = %s; var obligations = %s;' % (
            json.dumps([t.to_dict() for t in all_tickets]), json.dumps(committers), json.dumps(milestones), json.dumps(holidays), json.dumps(obligations)))
    


def main():
    application = webapp.WSGIApplication([
        ('/data/backlog/(.+)/', BacklogHandler),
        ('/data/milestone-tickets/', MilestoneTicketsHandler),
        ('/data/milestones/', MilestonesHandler),
        ], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
